package com.wx.core.process.message;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.pagehelper.PageHelper;
import com.wx.commons.ResultConstant;
import com.wx.core.process.BaseProcess;
import com.wx.core.process.BaseResult;
import com.wx.core.process.MsgXmlUtil;
import com.wx.core.process.ProcessResult;
import com.wx.core.process.WxServiceProcess;
import com.wx.core.vo.Image;
import com.wx.core.vo.MsgNews;
import com.wx.core.vo.MsgRequest;
import com.wx.core.vo.MsgResponseImage;
import com.wx.core.vo.MsgResponseNews;
import com.wx.core.vo.MsgResponseText;
import com.wx.core.vo.MsgResponseVoice;
import com.wx.core.vo.MsgText;
import com.wx.entity.WxImageReply;
import com.wx.entity.WxImageReplyExample;
import com.wx.entity.WxMulReply;
import com.wx.entity.WxMulReplyExample;
import com.wx.entity.WxPicReply;
import com.wx.entity.WxPicReplyExample;
import com.wx.entity.WxResource;
import com.wx.entity.WxResourceExample;
import com.wx.entity.WxTextReply;
import com.wx.entity.WxTextReplyExample;
import com.wx.entity.WxTextReplyExample.Criteria;
import com.wx.entity.WxVoiceReply;
import com.wx.entity.WxVoiceReplyExample;
import com.wx.flag.KeyWordType;
import com.wx.service.SysWxuserService;
import com.wx.service.WxImageReplyService;
import com.wx.service.WxMulReplyService;
import com.wx.service.WxPicReplyService;
import com.wx.service.WxResourceService;
import com.wx.service.WxTextReplyService;
import com.wx.service.WxVoiceReplyService;
import com.wx.util.StringUtils;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
/**
 * @desc 文本消息处理流程
 * @author Gavin
 * @date 2015-7-14
 * @time 下午5:12:35
 * @version 1.0
 */
public class TextMessageProcess extends BaseProcess{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Resource
	WxTextReplyService wxTextReplyService;
	@Resource
	WxPicReplyService wxPicReplyService;
	@Resource
	WxMulReplyService wxMulReplyService;
	@Resource
	WxVoiceReplyService wxVoiceReplyService;
	@Resource
	private  WxImageReplyService wxImageReplyService;
	@Resource
	WxResourceService wxResourceService;
	
	@Resource
	private SysWxuserService sysWxuserService;
	
	private volatile boolean isFirstRequset = true;
	
	private String serverAblolutlyPath;
	
	@Override
	public BaseResult process(HttpServletRequest req, HttpServletResponse res, MsgRequest msgRequest) {
		if(isFirstRequset){
			serverAblolutlyPath = getAbsolutPath(req);
			isFirstRequset = false;
		}
		ProcessResult result = null;
		
		//关键词回复
		result = getTextReply(msgRequest);
		if(result.getResult()!=null){
			return result;
		}
		//图文回复
		result = getPicReply(msgRequest);
		if(result.getResult()!=null){
			return result;
		}
		//多图文回复
		result = getMulPicReply(msgRequest);
		if(result.getResult()!=null){
			return result;
		}
		//语音回复
		result = getVoiceReply(msgRequest);
		if(result.getResult()!=null){
			return result;
		}
		
		result = getImageReply(msgRequest);
		if(result.getResult()!=null){
			return result;
		}
		
		//设置默认回复
		MsgText msgText = new MsgText();
		String defText = PropertiesUtils.getConfig("global_default_text_reply");
		msgText.setContent(defText==null?"欢迎使用！":defText);
		MsgResponseText msgResponseText = WxServiceProcess.getMsgResponseText(msgRequest, msgText);
		String xml = MsgXmlUtil.textToXml(msgResponseText);
		result.setResult(xml);
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	
	


	/**
	* @author: gavin
	* @date:   2015年7月15日
	* @Title:  getTextReply
	* @Description: 获取关键词文本回复
	* @param @param msgRequest
	* @param @return    设定文件
	* @return ProcessResult    返回类型
	* @throws
	 */
	private ProcessResult getTextReply(MsgRequest msgRequest){
		ProcessResult result = new ProcessResult();
		String content = msgRequest.getContent();
		try {
			//获取关键词信息
			WxTextReplyExample wxTextReplyExample = new WxTextReplyExample();
			Criteria cr1 = wxTextReplyExample.createCriteria();
			Criteria cr2 = wxTextReplyExample.createCriteria();
			cr1.andKeywordLike("%"+content+"%").andKeywordTypeEqualTo(2).andWxidEqualTo(msgRequest.getToUserName());
			cr2.andKeywordEqualTo(content).andKeywordTypeEqualTo(1).andWxidEqualTo(msgRequest.getToUserName());
			wxTextReplyExample.or(cr2);
			wxTextReplyExample.setOrderByClause(" keyword_type asc");
			
			PageHelper.startPage(1,1);
			List<WxTextReply> wxTextReplyList = wxTextReplyService.selectByExample(wxTextReplyExample);
			//组装发送消息
			if(wxTextReplyList!=null && wxTextReplyList.size()>0){
				MsgText msgText = new MsgText();
				msgText.setContent(wxTextReplyList.get(0).getContent());
				MsgResponseText msgResponseText = WxServiceProcess.getMsgResponseText(msgRequest, msgText);
				String xml = MsgXmlUtil.textToXml(msgResponseText);
				result.setResult(xml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	
	private ProcessResult getDefTextReply(ProcessResult result,WxTextReply wxTextReply,MsgRequest msgReq){
        try {
            //组装发送消息
            MsgText msgText = new MsgText();
            msgText.setContent(wxTextReply.getContent());
            MsgResponseText msgResponseText = WxServiceProcess.getMsgResponseText(msgReq, msgText);
            String xml = MsgXmlUtil.textToXml(msgResponseText);
            result.setResult(xml);
        } catch (Exception e) {
        	e.printStackTrace();
            result.setCode(ResultConstant.FAILUER);
            result.setErrmsg(e.getMessage());
        }
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }

	/**
	* @author: gavin
	* @date:   2015年7月15日
	* @Title:  getTextReply
	* @Description: 获取关键词单图文回复
	* @param @param msgRequest
	* @param @return    设定文件
	* @return ProcessResult    返回类型
	* @throws
	 */
	private ProcessResult getPicReply(MsgRequest msgRequest){
		ProcessResult result = new ProcessResult();
		try {
			//获取关键词信息
			WxPicReplyExample wxPicReplyExample = new WxPicReplyExample();
			com.wx.entity.WxPicReplyExample.Criteria cr1 = wxPicReplyExample.createCriteria();
			com.wx.entity.WxPicReplyExample.Criteria cr2 = wxPicReplyExample.createCriteria();
			cr1.andPKeywordLike("%"+msgRequest.getContent()+"%").andPKeywordTypeEqualTo(2).andWxidEqualTo(msgRequest.getToUserName());
			cr2.andPKeywordEqualTo(msgRequest.getContent()).andPKeywordTypeEqualTo(1).andWxidEqualTo(msgRequest.getToUserName());
			wxPicReplyExample.or(cr2);
			wxPicReplyExample.setOrderByClause(" p_keyword_type asc");
			
			PageHelper.startPage(1, 1);
			List<WxPicReply> wxPicReplyList = wxPicReplyService.selectByExample(wxPicReplyExample);
			
			//组装发送消息
			if(wxPicReplyList!=null && wxPicReplyList.size()>0){
				String xml = getResponseNews(msgRequest,wxPicReplyList);
				result.setResult(xml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	/*
	 * 获得关键字图片回复
	 */
	private ProcessResult getImageReply(MsgRequest msgRequest)
	{
		ProcessResult result = new ProcessResult();
		try{
			WxImageReplyExample example = new WxImageReplyExample();
			example.createCriteria().andKeywordLike("%"+msgRequest.getContent()+"%").andWxidEqualTo(msgRequest.getToUserName());
			PageHelper.startPage(1, 1);
			List<WxImageReply> wxImageReplyList = wxImageReplyService.list(example);
			if(wxImageReplyList != null && wxImageReplyList.size()>0){
				WxResourceExample wxResourceExample = new WxResourceExample();
				wxResourceExample.createCriteria().andRefTypeEqualTo(KeyWordType.TYPE_IMAGE.getValue()).andRefIdEqualTo(wxImageReplyList.get(0).getId());
				PageHelper.startPage(1, 1);
				List<WxResource> resList = wxResourceService.selectByExample(wxResourceExample);
				Image image = new Image();
				if(null!=resList&&resList.size()>0){
			    	image.setMediaId(resList.get(0).getMediaId());
				}
				MsgResponseImage msgResponseImage = WxServiceProcess.getMsgResponseImage(msgRequest, image);
				String imageToXml = MsgXmlUtil.imageToXml(msgResponseImage);
				result.setResult(imageToXml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	
	/*
	 * 获得默认图片回复
	 */
	private ProcessResult getDefImageReply(ProcessResult result,WxImageReply wxImageReply,MsgRequest msgRequest){
        try{
            WxResourceExample wxResourceExample = new WxResourceExample();
            wxResourceExample.createCriteria().andRefTypeEqualTo(KeyWordType.TYPE_IMAGE.getValue()).andRefIdEqualTo(wxImageReply.getId());
            PageHelper.startPage(1, 1);
            List<WxResource> wxResourceList = wxResourceService.selectByExample(wxResourceExample);
            if(wxResourceList==null || wxResourceList.size()==0) return null;
            String mediaId = wxResourceList.get(0).getMediaId();
            Image image = new Image();
            image.setMediaId(mediaId);
            //组装发送消息
            MsgResponseImage msgResponseImage = WxServiceProcess.getMsgResponseImage(msgRequest,image);
            String xml = MsgXmlUtil.imageToXml(msgResponseImage);
            result.setResult(xml);
        } catch (Exception e) {
        	e.printStackTrace();
            result.setCode(ResultConstant.FAILUER);
            result.setErrmsg(e.getMessage());
        }
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }
	
	/**
	 * 获取默认关键词单图文回复
	 * @Description 
	 * @author Steven
	 * @param msgRequest
	 * @return
	 */
	 private ProcessResult getDefPicReply(ProcessResult result,WxPicReply wxPicReply ,MsgRequest msgRequest){
        try {
            //获取关键词信息
            List<WxPicReply> wxPicReplyList = new ArrayList<WxPicReply>();
            wxPicReplyList.add(wxPicReply);
            //组装发送消息
            if(wxPicReplyList!=null && wxPicReplyList.size()>0){
                String xml = getResponseNews(msgRequest,wxPicReplyList);
                result.setResult(xml);
            }
        } catch (Exception e) {
        	e.printStackTrace();
            result.setCode(ResultConstant.FAILUER);
            result.setErrmsg(e.getMessage());
        }
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }
	
	/**
	* @author: gavin
	* @date:   2015年7月15日
	* @Title:  getTextReply
	* @Description: 获取关键词单图文回复
	* @param @param msgRequest
	* @param @return    设定文件
	* @return ProcessResult    返回类型
	* @throws
	 */
	private ProcessResult getMulPicReply(MsgRequest msgRequest){
		ProcessResult result = new ProcessResult();
		try {
			//获得多图文回复信息
			WxMulReplyExample wxMulReplyExample = new WxMulReplyExample();
			wxMulReplyExample.createCriteria().andKeywordEqualTo(msgRequest.getContent()).andWxidEqualTo(msgRequest.getToUserName());
			List<WxMulReply> wxMulReplyList = wxMulReplyService.selectByExample(wxMulReplyExample);
			List<WxPicReply> wxPicReplyList = new ArrayList<WxPicReply>();
			if(wxMulReplyList!=null && wxMulReplyList.size()>0){
				String ids = wxMulReplyList.get(0).getPicIds();
				if(StringUtils.isEmpty(ids)) return null;
				String[] arr = ids.split(",");
				if(arr==null || arr.length==0) return  null;
				List<Integer> idList = new ArrayList<>(arr.length);
				for(String str : arr){
					if(!StringUtils.isEmpty(str.trim())){
						idList.add(Integer.valueOf(str));
					}
				}
				for(Integer id : idList){
					WxPicReplyExample picExample = new WxPicReplyExample();
					picExample.createCriteria().andIdEqualTo(id);
					PageHelper.startPage(1, 1);
					List<WxPicReply> resList = wxPicReplyService.selectByExample(picExample);
					if(null != resList && resList.size()>0){
						WxPicReply bean = resList.get(0);
						wxPicReplyList.add(bean);
					}
				}
			}
			//组装发送消息
			if(wxPicReplyList!=null && wxPicReplyList.size()>0){
				String xml = getResponseNews(msgRequest, wxPicReplyList);
				result.setResult(xml);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	
	/**
	 * 获取默认多图文回复
	 * @Description 
	 * @author Steven
	 * @param msgRequest
	 * @return
	 */
	private ProcessResult getDefMulPicReply(ProcessResult result,WxMulReply wxMulReply,MsgRequest msgRequest){
        try {
            List<WxPicReply> wxPicReplyList = new ArrayList<WxPicReply>();
            String ids = wxMulReply.getPicIds();
            if(StringUtils.isEmpty(ids)) return null;
            String[] arr = ids.split(",");
            if(arr==null || arr.length==0) return  null;
            for(String str : arr){
                if(!StringUtils.isEmpty(str.trim())){
                    WxPicReply wxPicReply = wxPicReplyService.selectByPrimaryKey(Integer.valueOf(str));
                    wxPicReplyList.add(wxPicReply);
                }
            }
            //组装发送消息
            if(wxPicReplyList!=null && wxPicReplyList.size()>0){
                String xml = getResponseNews(msgRequest,wxPicReplyList);
                result.setResult(xml);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResultConstant.FAILUER);
            result.setErrmsg(e.getMessage());
        }
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }
	
	/**
	* @author: gavin
	* @date:   2015年7月15日
	* @Title:  getResponseNews
	* @Description: 获取消息
	* @param @return    设定文件
	* @return MsgResponseNews    返回类型
	* @throws
	 */
	private String getResponseNews(MsgRequest msgRequest,List<WxPicReply> wxPicReplyList){
		List<MsgNews> msgNewsList = new ArrayList<MsgNews>();
		wxPicReplyList.forEach(p->{
			MsgNews msgNews = new MsgNews();
			msgNews.setTitle(p.getTitle());
			msgNews.setPicpath(serverAblolutlyPath+p.getpImgHref());
			msgNews.setUrl(serverAblolutlyPath+"/pic/detail?id="+p.getId());
			msgNews.setFromurl(p.getArticleUrl());
			msgNews.setBrief(p.getpSummary());
			msgNewsList.add(msgNews);
		});
		MsgResponseNews msgResPonseNews = WxServiceProcess.getMsgResponseNews(msgRequest, msgNewsList);
		return MsgXmlUtil.newsToXml(msgResPonseNews);
	}
	
	/**
	* @author：Gavin 2015年7月23日
	* @Title: getVoiceReply
	* @Description: 关键词语音回复
	* @param @param msgRequest
	* @param @return    设定文件
	* @return ProcessResult    返回类型
	* @throws
	 */
	private ProcessResult getVoiceReply(MsgRequest msgRequest){
		ProcessResult result = new ProcessResult();
		try {
			//获取关键词信息
			WxVoiceReplyExample wxVoiceReplyExample = new WxVoiceReplyExample();
			wxVoiceReplyExample.createCriteria().andKeywordsEqualTo(msgRequest.getContent()).andWxidEqualTo(msgRequest.getToUserName());
			List<WxVoiceReply> wxVoiceReplyList = wxVoiceReplyService.selectByExample(wxVoiceReplyExample);
			
			//组装发送消息
			if(wxVoiceReplyList!=null && wxVoiceReplyList.size()>0){
				//获取mediaID
				WxResourceExample wxResourceExample = new WxResourceExample();
				wxResourceExample.createCriteria().andRefTypeEqualTo(KeyWordType.TYPE_RADIO.getValue()).andRefIdEqualTo(wxVoiceReplyList.get(0).getId());
				List<WxResource> wxResourceList = wxResourceService.selectByExample(wxResourceExample);
				if(wxResourceList!=null && wxResourceList.size()>0) {
					String mediaId = wxResourceList.get(0).getMediaId();
					MsgResponseVoice msgResponseVoice = WxServiceProcess.getMsgResponseVoice(msgRequest, mediaId);
					String xml = MsgXmlUtil.voiceToXml(msgResponseVoice);
					result.setResult(xml);
				}else{
					throw new NullPointerException("声音素材丢失:" + wxVoiceReplyList.get(0).getId());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(ResultConstant.FAILUER);
			result.setErrmsg(e.getMessage());
		}
		result.setCode(ResultConstant.SUCCESS);
		return result;
	}
	
	/**
	 * 获取默认语音回复
	 * @Description 
	 * @author Steven
	 * @param msgRequest
	 * @return
	 */
	private ProcessResult getDefVoiceReply(ProcessResult result,WxVoiceReply wxVoiceReply,MsgRequest msgRequest){
        try {
            WxResourceExample wxResourceExample = new WxResourceExample();
            wxResourceExample.createCriteria().andRefTypeEqualTo(KeyWordType.TYPE_RADIO.getValue()).andRefIdEqualTo(wxVoiceReply.getId());
            List<WxResource> wxResourceList = wxResourceService.selectByExample(wxResourceExample);
            if(wxResourceList==null || wxResourceList.size()==0) return null;
            String mediaId = wxResourceList.get(0).getMediaId();
            
            MsgResponseVoice msgResponseVoice = WxServiceProcess.getMsgResponseVoice(msgRequest, mediaId);
            String xml = MsgXmlUtil.voiceToXml(msgResponseVoice);
            result.setResult(xml);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(ResultConstant.FAILUER);
            result.setErrmsg(e.getMessage());
        }
        result.setCode(ResultConstant.SUCCESS);
        return result;
    }
	
}

